package com.dm0858.bianmin.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dm0858.bianmin.R;
import com.dm0858.bianmin.model.entity.NewsListData;
import com.dm0858.bianmin.model.response.ArticleCatResponse;
import com.dm0858.bianmin.model.response.ArticleListResponse;
import com.dm0858.bianmin.model.response.BannerResponse;
import com.dm0858.bianmin.ui.base.BaseActivity;
import com.dm0858.bianmin.ui.fragment.HomeFragment;
import com.dm0858.bianmin.ui.presenter.ArticleCatPresenter;
import com.dm0858.bianmin.ui.presenter.ArticleDetailPresenter;
import com.dm0858.bianmin.ui.presenter.ArticleListPresenter;
import com.dm0858.bianmin.utils.DateUtils;
import com.dm0858.bianmin.utils.DensityUtils;
import com.dm0858.bianmin.utils.ResourceReader;
import com.dm0858.bianmin.utils.UIUtils;
import com.dm0858.bianmin.view.IArticleCatView;
import com.dm0858.bianmin.view.IArticleDetailView;
import com.dm0858.bianmin.view.IArticleListView;
import com.dm0858.bianmin.view.ListViewFrame;
import com.google.gson.Gson;
import com.socks.library.KLog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static com.dm0858.bianmin.app.ApiConstant.BASE_SERVER_URL;

/**
 * Created by yelvqing on 2018/4/30.
 */

public class ZiXunActivity extends BaseActivity<ArticleListPresenter>  implements IArticleListView ,ListViewFrame.IXListViewListener{

    @Bind(R.id.orderbox)
    LinearLayout layout_tab;

    ArticleCatResponse bean;
    private int selectbtn=0;
    private int first_select=2;

    private Handler handler=null;
    private int p = 1;

    @Bind(R.id.liv_od_content)
    ListViewFrame liv_od_content;

    @Bind(R.id.tv_alert_no_order)
    TextView tv_alert_no_order;


    private List<NewsListData> madapter_data=new ArrayList<NewsListData>();
    MyAdapter myAdapter;

    @Override
    protected ArticleListPresenter createPresenter() {
        return new ArticleListPresenter(this);
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_article_list;
    }

    @Override
    public void onGetArticleList(ArticleListResponse newList) {
        if(newList.data==null||newList.data.isEmpty()||newList.data.equals("[]"))
        {
            if(p>1) UIUtils.showToast("没有更多内容了");
            else
            {
                liv_od_content.setVisibility(View.GONE);

                tv_alert_no_order.setVisibility(View.VISIBLE);
            }


        }
        else {

            for (int i = 0; i < newList.data.size(); i++) {
                madapter_data.add(newList.data.get(i));
            }
            myAdapter = new MyAdapter();
            liv_od_content.setVisibility(View.VISIBLE);
            tv_alert_no_order.setVisibility(View.GONE);
            liv_od_content.setAdapter(myAdapter);

            myAdapter.notifyDataSetChanged();
            onLoad();
        }

    }


    /**
     * 正在加载时回调
     */
    private void onLoad() {
        liv_od_content.stopRefresh();
        liv_od_content.stopLoadMore();
    }


    @Override
    public void onError() {

    }

    @Override
    public void initView() {


    }

    @Override
    public void initData() {

        handler=new Handler();
        getCatlist();




//        setTabSelected(btn2);
//        setBtnAction(2);

    }

    @Override
    public void initListener() {






    }

    @OnClick(R.id.iv_back)
    public void onViewClicked() {
        finish();
    }


    private void setTabSelected(Button btnSelected) {
        Drawable selectedDrawable = ResourceReader.readDrawable(this, R.drawable.shape_nav_indicator);
        int screenWidth = DensityUtils.getScreenSize(this)[0];
        int right = screenWidth / 4;
        selectedDrawable.setBounds(0, 0, right, DensityUtils.dipTopx(this, 3));
        btnSelected.setTextColor(this.getResources().getColor(R.color.colorAccent));
        btnSelected.setSelected(true);
        btnSelected.setCompoundDrawables(null, null, null, selectedDrawable);
        int size = layout_tab.getChildCount();
        for (int i = 0; i < size; i++) {
            if (btnSelected.getId() != layout_tab.getChildAt(i).getId()) {
                layout_tab.getChildAt(i).setSelected(false);
                ((Button) layout_tab.getChildAt(i)).setTextColor(this.getResources().getColor(R.color.text_color));
                ((Button) layout_tab.getChildAt(i)).setCompoundDrawables(null, null, null, null);
            }
        }
    }

    private void setBtnAction(int flag)
    {
        if (madapter_data.size()>0) {
            madapter_data.clear();
            myAdapter.notifyDataSetChanged();
        }
        p=1;
        selectbtn=flag;
        mPresenter.getArticleList(selectbtn+"",p+"");
    }


    private  void getCatlist()
    {
        OkHttpClient client = new OkHttpClient.Builder().readTimeout(5, TimeUnit.SECONDS).build();
        Request request = new Request.Builder().url(BASE_SERVER_URL+"phpapi/info.php?func=getNewsCat")
                .get().build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("Fail");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

//                System.out.println(response.body().string());

                final  String str = response.body().string();
                Gson gson = new Gson();
                bean = gson.fromJson(str,
                        ArticleCatResponse.class);
                handler.post(udpUIRunnable); //向Handler post runnable对象


            }
        });
    }
    // 构建Runnable对象，并在runnable中更新UI
    Runnable   udpUIRunnable=new  Runnable(){
        @Override
        public void run() {
            initCatBtn();
            initlist();

        }
    };

    private  void initCatBtn()
    {
        for (int i=0;i<bean.data.size();i++)
        {
            Button btn = new Button(this);
            btn.setId(i);
            int selectbtn1=Integer.parseInt(bean.data.get(i).id);
            btn.setText(bean.data.get(i).catname);
            btn.setBackgroundColor(Color.TRANSPARENT);
            btn.setTextColor(this.getResources().getColor(R.color.text_color));
            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    setTabSelected(btn);
                    if (madapter_data.size()>0) {
                        madapter_data.clear();
                        myAdapter.notifyDataSetChanged();
                    }
                    setBtnAction(selectbtn1);

                }
            });
            layout_tab.addView(btn);
        }



    }

    private  void initlist()
    {
        first_select = 2;
        mPresenter.getArticleList(first_select+"",p+"");
        liv_od_content.setPullLoadEnable(true);
        liv_od_content.setXListViewListener(this);
        registerForContextMenu(liv_od_content);
        liv_od_content.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(ZiXunActivity.this, ArticleDetailActivity.class);
                intent.putExtra(ArticleDetailActivity.id, madapter_data.get(arg2-1).id);
                startActivity(intent);

            }
        });
    }

    @Override
    public void onRefresh() {
        if (madapter_data.size()>0) {
            madapter_data.clear();
        }
        p=1;
        if(selectbtn==0)
            mPresenter.getArticleList(first_select+"",p+"");
        else
            mPresenter.getArticleList(selectbtn+"",p+"");
    }

    @Override
    public void onLoadMore() {
        p++;
        if(selectbtn==0)
            mPresenter.getArticleList(first_select+"",p+"");
        else
            mPresenter.getArticleList(selectbtn+"",p+"");
    }


    static class ViewHolder {
        public TextView addexam_list_item_text;


    }

    public class MyAdapter extends BaseAdapter {

        ViewHolder holder = null;
        @Override
        public int getCount() {
            int count= madapter_data.size();
            return count;
        }

        @Override
        public Object getItem(int arg0) {
            int arg1=arg0;
            if (madapter_data.size() < arg0) {
                return madapter_data.get(0);
            }
            return madapter_data.get(arg0);
        }

        @Override
        public long getItemId(int arg0) {
            int arg1=arg0;
            // TODO Auto-generated method stub
            return arg1;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup arg2) {

            convertView= LayoutInflater.from(ZiXunActivity.this).inflate(R.layout.item_text_news, null);
            ImageView fruitImage = (ImageView) convertView.findViewById(R.id.news_image);//获取该布局内的图片视图
            TextView fruitName = (TextView) convertView.findViewById(R.id.news_name);//获取该布局内的文本视图
//        fruitImage.setImageResource();//为图片视图设置图片资源

            if (getCount() < position) {

            }else {
                Glide.with(ZiXunActivity.this).load(madapter_data.get(position).address).into(fruitImage);
                fruitName.setText(madapter_data.get(position).title);//为文本视图设置文本内容
            }


//            TextView tiametxt = (TextView) convertView.findViewById(R.id.news_time);//获取该布局内的文本视图
//            String timestr = DateUtils.dataOne(madapter_data.get(position).addtime);
//            tiametxt.setText(DateUtils.timedate(timestr));

            return convertView;




        }


    }


}
